package com.qianfeng.smartmeeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qianfeng.smartmeeting.entity.UserEntity;
import com.qianfeng.smartmeeting.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username);
        UserEntity user = userMapper.selectOne(wrapper);

        if(user == null){
            throw new RuntimeException("用户名错误");
        }

        // 角色前缀必须是"ROLE_"（Spring Security规范）
        String role = user.getUserType() == 1 ? "ADMIN" : "USER";

        return User
                .withUsername(user.getUserName())
                .password(user.getUserPassword())
                .roles(role)
                .build();
    }
}
